package com.example.togethermove.utils;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;


import com.example.togethermove.config.Constants;
import com.example.togethermove.utils.rsa.Signature;

import java.security.MessageDigest;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * @ClassName: StringUtils
 * @Author: csl
 * @Date:
 * @Description: 工具类
 */
public class StringUtilone {

    public static boolean isNull(String str) {
        return (str == null || str.length() == 0 || str.equalsIgnoreCase("null")) ? true : false;
    }

    public static String formatUrl(String url) {
        if (isNull(url)) {
            return url;
        } else {
            return url.replaceAll("&amp;", "&");
        }
    }

    public static boolean isNull(TextView tv) {
        return StringUtilone.isNull(tv.getText().toString());
    }


    //验证手机号
    public static boolean isMobileNO(String mobiles) {

//        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(17[6,7,8])|(18[0,5-9]))\\ZYEndorseOrderDetail{8}$");

        Pattern p = Pattern.compile("^1\\d{10}$");

        Matcher m = p.matcher(mobiles);

        return m.matches();

    }

    /**
     * 得到String的MD5码
     *
     * @param srcString 将要加密码的字符串
     * @return String 加密后的字符串
     */
    public static String getMD5(String srcString) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(srcString.getBytes("UTF8"));
            byte s[] = md.digest();
            String result = "";
            for (int i = 0; i < s.length; i++) {
                result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);
            }
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param client
     * @param token
     * @param datetime
     * @param data
     * @param reqno
     * @return MD5加密
     */
    public static String getMd5(String client, String token, String datetime, String data, String reqno) {
        return StringUtilone.getMD5(Signature.md5key + reqno + client + token + datetime + data);
    }

    public static String doEmojiCharInterceptor(String s) {
        if (s == null || s.length() == 0)
            return s;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            if (!isEmojiCharacter(new Integer(s.charAt(i)))) {
                sb.append(s.charAt(i));
            }
        }
        String ss = sb.toString();
        return ss;
    }

    public static boolean isEmojiCharacter(int codePoint) {
        return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }

    private static Random random = new Random();

    public static String generateId() {
        StringBuilder sb = new StringBuilder();
        sb.append("A");
        for (int i = 0; i < 5; i++) {
            char aa = (char) (random.nextInt(26) + 65);
            sb.append(aa);
        }
        sb.append(System.currentTimeMillis());
        return sb.toString();
    }

    /**
     * 获取设备号
     *
     * @param context
     * @return
     */
    @SuppressWarnings("deprecation")
    public static String getDeviceId(Context context) {
        SharedPreferences sp;
//        sp = context.getSharedPreferences("Userinfo", Context.MODE_WORLD_READABLE);
        String eeviceId = "";
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager telephonyMgr = (TelephonyManager)context. getSystemService(TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                eeviceId = telephonyMgr.getImei();
            } else {
//                eeviceId = telephonyMgr.getDeviceId();
            }
        }
        if (StringUtilone.isNull(eeviceId)) {
//            SharedPreferences.Editor editor = sp.edit();
//            eeviceId = sp.getString(Constants.DEVICE_ID_KEY, "");
            eeviceId = SPUtilsone.getStringValue(Constants.DEVICE_ID_KEY, "");

            if (StringUtilone.isNull(eeviceId)) {
                eeviceId = StringUtilone.randomNums(15);
                SPUtilsone.putStringValue(Constants.DEVICE_ID_KEY, eeviceId);
//                editor.putString(Constants.DEVICE_ID_KEY, eeviceId);
//                editor.commit();
            }
        }
        return eeviceId;
    }

    public static String randomNums(int length) {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            stringBuffer.append(random.nextInt(9) + 1);
        }
        return stringBuffer.toString();
    }

    public static String listToString(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ";");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }
    /**
     * 返回 唯一的虚拟 ID
     * @return ID
     */
    public static String getUniquePsuedoID() {
        String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);

        // API >= 9 的设备才有 android.os.Build.SERIAL
        // http://developer.android.com/reference/android/os/Build.html#SERIAL
        // 如果用户更新了系统或 root 了他们的设备，该 API 将会产生重复记录
        String serial = null;
        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial";
        }

        // 最后，组合上述值并生成 UUID 作为唯一 ID
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }
}
